//
//  AppListViewController.m
//  LimitFree
//
//  Created by lijinghua on 16/3/1.
//  Copyright © 2016年 lijinghua. All rights reserved.
//

#import "AppListViewController.h"
#import "AppListModel.h"
#import "AppListTableViewCell.h"
#import "AppDetailViewController.h"
#import "SearchAppViewController.h"
#import "CategoryViewController.h"

@interface AppListViewController ()<UISearchBarDelegate,CategorySelectProtocol>

@property(nonatomic)BOOL isRefreshing;
@property(nonatomic)BOOL isLoadingMore;

@end

@implementation AppListViewController

- (id)init{
    if (self = [super init]) {
        self.navigationStyle = LFNavigationBothStyle;
        self.appListArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initParamater];
    [self.view addSubview:self.tableView];
    [self createRefreshHeadView];
    [self createRefreshFootView];
    [self createSearchBar];
    [self fetchAppData];
}

- (void)createRefreshHeadView{
    __weak typeof(self) wSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (wSelf.isRefreshing) {
            return ;
        }
        wSelf.isRefreshing  = YES;
        [wSelf initParamater];
        [wSelf fetchAppData];
    }];
}

- (void)createRefreshFootView{
    __weak typeof(self) wSelf = self;
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (wSelf.isLoadingMore) {
            return ;
        }
        wSelf.isLoadingMore = YES;
        wSelf.page++;
        [wSelf fetchAppData];
    }];
}

- (void)endRefreshing{
    if (self.isRefreshing) {
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
        self.isRefreshing = NO;
    }
    if (self.isLoadingMore) {
        self.isLoadingMore = NO;
        [self.tableView footerEndRefreshing];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)initParamater{
    self.page = 0;
    self.category_id = @"0";
}

#pragma mark - 导航栏事件
- (void)handleNavLeftButtonClick:(UIButton*)button{
        CategoryViewController *categoryViewController = [[CategoryViewController alloc]init];
        //把自身作为代理
        categoryViewController.delegate = self;
        categoryViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:categoryViewController animated:YES];
}

#pragma mark - CategorySelectProtocol
- (void)category:(CategoryViewController*)viewController didSelectCategroyId:(NSString*)categoryId{
    self.category_id = categoryId;
    //重新新加载数据
    self.page = 0;
    [self fetchAppData];
}

#pragma mark - CustomUI

- (void)createSearchBar
{
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    searchBar.placeholder = @"60万应用等着你搜";
    //设置自身为搜索的代理，这里搜索的状态就会通过相应的代理方法通知我们
    searchBar.delegate = self;
    
    self.tableView.tableHeaderView = searchBar;
}

- (UITableView*)tableView{
    if (_tableView ==  nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 49)];
        _tableView.dataSource = self;
        _tableView.delegate   = self;
        //删除分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self registTableViewCell];
    }
    return _tableView;
}

- (void)registTableViewCell{
    UINib *nib = [UINib nibWithNibName:@"AppListTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"cellId"];
}

#pragma mark - 数据获取和处理
- (void)fetchAppData
{
    //先从缓存中获取数据，如果缓存中的数据失效（一个小时），从服务器加载
    if(![self fetchAppDataFromLocal]){
        [self fetchAppDataFromServer];
    }
}

//返回值，读取本地缓存是否成功
- (BOOL)fetchAppDataFromLocal{
    NSString *url = [self composeServerUrl];
    NSData * data = [[LimitFreeCacheManager sharedInstance] readData:url];
    if (data == nil) {
        //没有成功从缓存中读取数据
        [self endRefreshing];
        return NO;
    }
    //把数据解归档成对象
    id readObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    //解析并显示
    [self parseRespondsData:readObject];
    [self.tableView reloadData];
    [self endRefreshing];
    return YES;
}

- (void)fetchAppDataFromServer{
    //掉落动画
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleDrop];
    [MMProgressHUD showWithTitle:@"努力加载中..."];
    
    
//------------------------?????????????????
    NSString *url = [self composeServerUrl];
    
    //使用网络请求层获取数据
    [[NetDataEngine sharedInstance] requestAppList:url success:^(id respondObject) {
        //动画 加载成功
        [MMProgressHUD dismissWithSuccess:@"加载成功"];
        //成功后，解析数据
        [self parseRespondsData:respondObject];
        //刷表
        [self.tableView reloadData];
        //结束刷新
        [self endRefreshing];
        
    } falied:^(NSError *error) {
        //动画 加载失败
        [MMProgressHUD dismissWithError:@"数据加载失败"];
        //失败后提示
        NSLog(@"%@",error);
        //结束刷新
        [self endRefreshing];
    }];
}

- (void)cacheFirstPageData:(id)respondsObject{
    //把第一页的最原始的数据缓存下来
    if (![[LimitFreeCacheManager sharedInstance] isCachedUrlValidate:[self composeServerUrl]]) {
        NSData * saveDate = [NSKeyedArchiver archivedDataWithRootObject:respondsObject];
        [[LimitFreeCacheManager sharedInstance] saveData:saveDate url:[self composeServerUrl]];
    }
}

- (void)addToDataSource:(NSArray*)modelArray originalObject:(id)respondsObject{
    if (self.page == 0) {
        [self.appListArray removeAllObjects];
        [self.appListArray addObjectsFromArray:modelArray];
        [self cacheFirstPageData:respondsObject];
    }else{
        [self.appListArray addObjectsFromArray:modelArray];
    }
}

- (void)parseRespondsData:(id)respondsObject{
    //为了给viewcontroller瘦身，把数据解析model中
    NSArray *modelArray = [AppListModel parseRespondsData:respondsObject];
    [self addToDataSource:modelArray originalObject:respondsObject];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    //让cancle 按钮显示
    searchBar.showsCancelButton = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
    return YES;
}

//点击cancel 按钮调用的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //结束搜索状态
    [searchBar resignFirstResponder];
    searchBar.text = @"";
}

//点击键盘上的search按钮调用的代理方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString *searchText = searchBar.text;
    if (searchText.length > 0) {
        //推入一个搜索控制器，执行搜索
        SearchAppViewController  *searchViewController = [[SearchAppViewController alloc]init];
        
        //关键字
        searchViewController.keyword = searchText;
        
        //把页面类型传递过去
        searchViewController.fromType = self.type;
        
        [self.navigationController pushViewController:searchViewController animated:YES];
        
        [searchBar resignFirstResponder];
    }
}

#pragma mark - UITableViewDataSource And Deleagte
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.appListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AppListTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];
    AppListModel *model = self.appListArray[indexPath.row];
    [cell updateWithModel:model atIndexPath:indexPath type:self.type];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDetailViewController *detailViewController = [[AppDetailViewController alloc]init];
    AppListModel *model = self.appListArray[indexPath.row];
    detailViewController.applicationId = model.applicationId;
    [self.navigationController pushViewController:detailViewController animated:YES];
}



@end
